package com.concurrent.coline.part5.tools;

import java.util.concurrent.CountDownLatch;

/**
 * 类说明：演示CountDownLatch，有5个初始化的线程，6个扣除点，
 * 扣除完毕以后，主线程和业务线程才能继续自己的工作
 */
public class UseCountDownLatch {

    static CountDownLatch latch = new CountDownLatch(6);

    //初始化线程(只有一步，有4个)
    private static class InitThread implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " do business");
            latch.countDown();//初始化线程完成工作了，countDown方法只扣减一次；
            System.out.println(Thread.currentThread().getName() + " countDown finish");

        }
    }

    //业务线程
    private static class BusiThread implements Runnable {

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " begin await");
                latch.await();
                System.out.println(Thread.currentThread().getName() + " do business");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //单独的初始化线程,初始化分为2步，需要扣减两次
        new Thread("countDown_twice_thread") {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " first countDown");
                latch.countDown();//每完成一步初始化工作，扣减一次
                System.out.println(Thread.currentThread().getName() + " second countDown");
                latch.countDown();//每完成一步初始化工作，扣减一次
            }
        }.start();

        new Thread(new BusiThread(), "await_business_thread").start();

        for (int i = 0; i <= 3; i++) {
            Thread thread = new Thread(new InitThread());
            thread.start();
        }
    }
}
